<template>
	<div class="login-container">
		<div class="bg-login"></div>
		<el-form
			ref="loginForm"
			:model="loginForm"
			:rules="loginRules"
			class="login-form"
			auto-complete="on"
			label-position="left"
			@keyup.enter.native="handleLogin"
		>
			<div class="login-content">
				<div class="bg-header"></div>
				<div class="title-container">
					<!-- <svg-icon icon-class="bg-login" class="login_logo" /> -->
					<h3 class="title">{{ $t('common.backend_manage') }}</h3>
				</div>
				<el-form-item prop="username">
					<span class="svg-container">
						<svg-icon icon-class="user" class="svg-active" />
					</span>
					<el-input
						ref="username"
						v-model="loginForm.username"
						:placeholder="$t('common.login.username_placeholder')"
						name="username"
						type="text"
						tabindex="1"
						auto-complete="off"
					/>
				</el-form-item>

				<el-form-item prop="password">
					<span class="svg-container">
						<svg-icon icon-class="password" class="svg-active" />
					</span>
					<el-input
						:key="passwordType"
						ref="password"
						v-model="loginForm.password"
						:type="passwordType"
						:placeholder="$t('common.login.password_placeholder')"
						name="password"
						tabindex="2"
						oninput="value=value.replace(/(^\s*)|(\s*$)/g ,'')"
						auto-complete="off"
					/>
					<span class="show-pwd" @click="showPwd">
						<svg-icon
							:icon-class="
								passwordType === 'password' ? 'eye' : 'eye-open'
							"
						/>
					</span>
				</el-form-item>
				<el-form-item prop="googleAuthCode">
					<span class="svg-container">
						<svg-icon icon-class="security" class="svg-active" />
					</span>
					<el-input
						ref="security"
						v-model="loginForm.googleAuthCode"
						:placeholder="valaditeKeyTips"
						name="googleAuthCode"
						type="text"
						tabindex="3"
						maxlength="6"
						@input="
							loginForm.googleAuthCode = loginForm.googleAuthCode.replace(
								/[^0-9]+/g,
								''
							)
						"
					/>
				</el-form-item>
				<div
					class="codeSwitchSpan"
					@click="merchantCodeSwitchFun()"
					v-show="!merchantCodeSwitch"
				>
					<span>输入商户编码</span>
					<span style="color: #a0a3a3;">默认自动带入‘DZSH’商户</span>
				</div>
				<el-form-item prop="merchantCode" v-show="merchantCodeSwitch">
					<span class="svg-container">
						<svg-icon icon-class="security" class="svg-active" />
					</span>
					<el-input
						v-model="loginForm.merchantCode"
						:placeholder="
							$t('common.login.merchantCode_placeholder')
						"
						type="text"
						tabindex="4"
					/>
				</el-form-item>
				<!-- <el-form-item style="border: none;">
					<div
						id="captcha"
						style="width: 100%"
						:class="
							captchaConfig.config.product === 'bind'
								? 'hideHeight'
								: ''
						"
					>
						<GeetestCaptcha :captcha-config="captchaConfig" />
					</div>
				</el-form-item> -->
				<div class="login-btn" @click.prevent="handleLogin">
					<i v-show="loading" class="el-icon-loading"></i>
					<span>{{ $t('common.login.login') }}</span>
				</div>
				<div
					class="codeSwitchSpan"
					style="justify-content: center;"
					@click="reloadPage()"
				>
					<span>刷新页面</span>
				</div>
			</div>
		</el-form>
		<!-- <div class="bottom-tips">
			Copyright &copy; OBQJ, All Rights Reserved
			<br />
			助力打造最强现金网
		</div> -->
		<div class="select-wrapper">
			<lang-select v-if="showLangSelect" />
		</div>
	</div>
</template>

<script>
import report from '@/api'
import Finger from '@/utils/fingerprintjs2'
import LangSelect from '@/components/LangSelect'
// import GeetestCaptcha from '@/components/GeetestCaptcha'
export default {
	name: 'Login',
	components: { LangSelect },
	// GeetestCaptcha
	data() {
		return {
			loginForm: {
				username: '',
				password: '',
				googleAuthCode: '',
				merchantCode: 'DZSH' // BWZK
				// geetesValidate: false
			},
			loading: false,
			passwordType: 'password',
			redirect: undefined,
			baseUrl: process.env.VUE_APP_BASE_API,
			timestamp: +new Date(),
			version: '',
			captchaConfig: {
				config: {
					captchaId: process.env.VUE_APP_CAPTCHA_ID,
					product: 'popup',
					nativeButton: {
						width: '100%'
					},
					// hideBar: ['feedback'],
					protocol: 'https://'
				},
				handler: this.captchaHandler
			},
			captchaObj: null,
			valaditeKeyTips: undefined,
			loginRules: {
				username: [
					{
						required: true,
						message: this.$t('common.login.username_placeholder'),
						trigger: 'blur'
					}
				],
				password: [
					{
						required: true,
						message: this.$t('common.login.password_placeholder'),
						trigger: 'blur'
					}
				],
				googleAuthCode: [
					{
						required: true,
						message: this.$t('common.please_enter_validate_key'),
						trigger: 'blur'
					}
				],
				merchantCode: [
					{
						required: true,
						message: this.$t(
							'common.login.merchantCode_placeholder'
						),
						trigger: 'blur'
					}
				]
			},
			merchantCodeSwitch: false
		}
	},
	computed: {
		showLangSelect() {
			// FIXME 隐藏切换语言
			return false
			// return this.$store.getters.langList?.length > 1
		},
		language() {
			return this.$store.getters.language
		}
	},
	watch: {
		$route: {
			handler: function(route) {
				this.redirect = route.query && route.query.redirect
			},
			immediate: true
		}
	},
	created() {
		this.getValidateKeyType()
	},
	mounted() {
		// this.geetestStatus && this.onInitGeetest()
		this.$store.dispatch('app/queryLanguageList')
	},
	methods: {
		reloadPage() {
			location.reload()
		},
		merchantCodeSwitchFun() {
			this.loginForm.merchantCode = ''
			this.merchantCodeSwitch = true
		},
		// 获取密钥验证方式
		async getValidateKeyType() {
			// 默认提示信息
			await this.$api
				.getSystemValidateKeyType()
				.then((res) => {
					// 验证码类型:1-谷歌验证码 2-图形验证码（暂未使用） 3-海月盾
					const validateKeyType = res?.data?.verifyCodeType || 1
					if (validateKeyType === 3) {
						// 海月盾密钥
						this.valaditeKeyTips = this.$t(
							'common.please_enter_seamoon_key'
						)
					} else {
						// 谷歌密钥
						this.valaditeKeyTips = this.$t(
							'common.please_enter_google_key'
						)
					}
				})
				.catch(() => {
					// 默认谷歌密钥
					this.valaditeKeyTips = this.$t(
						'common.please_enter_google_key'
					)
				})
			this.loginRules.googleAuthCode = [
				{
					required: true,
					message: this.valaditeKeyTips,
					trigger: 'blur'
				}
			]
		},
		// 极验验证
		captchaHandler(captchaObj) {
			this.captchaObj = captchaObj
			captchaObj
				.appendTo('#captcha')
				.onReady(function() {
					console.log('ready')
				})
				.onNextReady(function() {
					console.log('nextReady')
				})
				.onBoxShow(function() {
					document.querySelector(
						'.geetest_footer_right'
					).style.display = 'none'
					document.querySelector('.geetest_feedback').style.display =
						'none'
				})
				.onError(function(e) {
					console.log(e)
				})
				.onSuccess(async () => {
					const {
						captcha_id,
						captcha_output,
						gen_time,
						lot_number,
						pass_token
					} = captchaObj.getValidate()
					try {
						const validate = await report.geetestValidate({
							captchaId: captcha_id,
							captchaOutput: captcha_output,
							genTime: gen_time,
							lotNumber: lot_number,
							passToken: pass_token
						})
						this.loginForm = {
							...this.loginForm,
							geetesValidate: validate.code === 200
						}
					} catch (error) {
						this.loginForm.geetesValidate = false
						captchaObj.reset()
					}

					// captchaObj.reset();
				})
		},
		// 兼容ie input 失去 再 聚焦 光标从头开始
		fixInput(obj) {
			const nodes = obj.$el.childNodes[1]
			nodes.focus() // 解决ff不获取焦点无法定位问题
			if (window.getSelection) {
				// ie11 10 9 ff safari
				var max_Len = nodes.value.length // text字符数
				nodes.setSelectionRange(max_Len, max_Len)
			} else if (document.selection) {
				// ie10 9 8 7 6 5
				var range = nodes.createTextRange() // 创建range
				range.collapse(false) // 光标移至最后
				range.select() // 避免产生空格
			}
		},
		showPwd() {
			if (this.passwordType === 'password') {
				this.passwordType = ''
			} else {
				this.passwordType = 'password'
			}
			this.$nextTick(() => {
				this.fixInput(this.$refs.password)
			})
		},
		handleLogin() {
			// if (!this.loginForm.geetesValidate) {
			// 	this.$message({
			// 		type: 'info',
			// 		message: this.$t('请进行校验'),
			// 		duration: 10 * 100
			// 	})
			// 	return false
			// }
			this.$refs.loginForm.validate((valid) => {
				if (valid && !this.loading) {
					this.loading = true
					Finger.loadUuid().then((res) => {
						this.loginForm.finger = res
						this.$store
							.dispatch('user/login', this.loginForm)
							.then(() => {
								this.$router.push({
									path: this.redirect || '/'
								})
								this.loading = false
							})
							.catch(() => {
								this.timestamp = +new Date()
								this.loading = false
								// this.captchaObj.reset()
								this.loginForm = {
									...this.loginForm,
									geetesValidate: false
								}
							})
					})
				} else {
					// this.captchaObj.reset()
					this.loginForm = {
						...this.loginForm,
						geetesValidate: false
					}
					return false
				}
			})
		}
	}
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #f1f2f3;
$light_gray: #fff;
$cursor: #999;
$bgc: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
	.login-container .el-input input {
		color: $cursor;
	}
}

/* reset element-ui css */
.login-container {
	min-height: 100%;
	width: 100%;
	//background-color: $bgc;
	overflow: hidden;
	background-size: cover;
	#captcha {
		height: 50px;
		&.hideHeight {
			height: 0;
		}
	}
	// background-position: fixed; /* Internet Explorer 7/8 */
	.login-form {
		position: relative;
		width: 500px;
		max-width: 100%;
		padding: 160px 35px 0;
		margin: 0 auto;
		overflow: hidden;
	}

	.logo {
		text-align: center;
		margin-bottom: 19px;
	}

	.bg-login {
		position: absolute;
		width: 100%;
		max-width: 100%;
		height: 220px;
		margin: 0 auto;
		top: 291px;
		background: url('../../assets/img/bg-login.jpg') no-repeat;
		background-size: cover;
	}

	.bg-header {
		width: 100%;
		height: 10px;
		position: absolute;
		background-color: #007bf9;
		box-shadow: 0 0 10px rgba(25, 81, 134, 0.35);
		top: -10px;
		left: 0.5px;
	}

	.login-content {
		padding: 8% 12% 500px 12%;
		height: 580px;
		background-size: cover;
		background-color: #ffffff;
		border-radius: 5px;
		border: 0.5px solid #ccc;
		box-shadow: 0 0 10px rgba(25, 81, 134, 0.35);
		z-index: 10;
		position: relative;
	}

	h3 {
		margin: 0 0 32px 0;
		text-align: center;
		font-family: MicrosoftYaHei;
		font-size: 32px;
		font-weight: normal;
		font-stretch: normal;
		letter-spacing: 0;
		color: #fff;
	}

	.el-form-item {
		box-sizing: border-box;
		width: auto;
		height: 50px;
		margin: 0 auto;
		margin-bottom: 25px;
		color: #999;
		border-radius: 5px;
		border: 1px solid #ccc;
		.el-input {
			display: inline-block;
			height: 47px;
			width: 75%;
			min-width: 100px;
			input {
				background: transparent;
				border: 0;
				-webkit-appearance: none;
				border-radius: 0;
				padding: 12px 5px 12px 15px;
				color: #999;
				height: 47px;
				caret-color: $cursor;
				&:-webkit-autofill {
					box-shadow: 0 0 0 1000px $bg inset !important;
					-webkit-text-fill-color: $cursor !important;
				}
			}
		}
	}

	.el-form-item:focus-within .svg-active {
		color: #0b7dfa;
	}

	.el-form-item:focus-within .el-form-item__error {
		display: none;
	}

	.el-form-item:focus-within {
		border: 1px solid #0b7dfa;
		border-radius: 5px;
	}

	.login-btn {
		background-color: rgba(0, 121, 254, 1);
		height: 51px;
		cursor: pointer;
		border-radius: 5px;
		text-align: center;
		font-family: MicrosoftYaHei;
		font-size: 20px;
		color: #fff;
		line-height: 51px;
	}

	.login-btn:hover {
		cursor: pointer;
		opacity: 0.8;
	}

	.aActive {
		color: #fff !important;
	}

	.switch-language a {
		margin-top: 46px;
		font-family: MicrosoftYaHei;
		text-decoration: underline;
		font-size: 18px;
		font-weight: normal;
		font-stretch: normal;
		letter-spacing: 0;
		color: #8a90a5;
	}

	.svg-container {
		padding: 3px 5px 6px 15px;
		color: $dark_gray;
		vertical-align: middle;
		width: 35px;
		display: inline-block;
		font-size: 18px;
	}

	.title-container {
		position: relative;
		text-align: center;
		.login_logo {
			width: 80px;
			height: 80px;
			margin: 0 auto;
			vertical-align: center;
		}

		.title {
			font-family: 'Microsoft Yahei';
			font-weight: normal;
			font-size: 26px;
			padding-top: 20px;
			color: $light_gray;
			margin: 0 auto 20px auto;
			text-align: center;
			color: #0079fe;
		}
	}

	.show-pwd {
		position: absolute;
		right: 10px;
		top: 4px;
		font-size: 16px;
		color: $dark_gray;
		cursor: pointer;
		user-select: none;
	}

	.kaptcha {
		height: 50px;
		border-radius: 10px;
	}

	.version {
		position: fixed;
		right: 10px;
		bottom: 10px;
		color: #007bf9;
	}

	.bottom-tips {
		position: fixed;
		bottom: 30px;
		text-align: center;
		left: 50%;
		font-size: 12px;
		color: #ccc;
		transform: translate(-50%, 0);
	}
	.codeSwitchSpan {
		color: #0079fe;
		margin: 20px 0;
		font-size: 13px;
		cursor: pointer;
		display: flex;
		justify-content: space-between;
	}
}
.select-wrapper {
	width: 120px;
	position: absolute;
	top: 20px;
	right: 20px;
}
</style>
